import { BasicLayout, BlankLayout, PageView, RouteView } from '@/layouts'
import { useUserStore } from '@/store/modules/user'
import { asyncRouteDefine } from '@/config/appConfig'
import { message } from 'ant-design-vue'

// 防抖时间配置（2秒）
const DEBOUNCE_TIME = 2000

// 前端路由组件表
const constantRouterComponents = Object.assign({
  BasicLayout: { component: BasicLayout },
  BlankLayout: { component: BlankLayout },
  RouteView: { component: RouteView },
  PageView: { component: PageView },
  '403': () => import('@/views/exception/403.vue'),
  '404': () => import('@/views/exception/404.vue'),
  '500': () => import('@/views/exception/500.vue')
}, asyncRouteDefine)

// 404路由配置
const notFoundRouter = {
  path: '*',
  component: () => import('@/views/exception/404.vue')
}

// 根路由配置
const rootRouter = {
  name: 'index',
  path: '/',
  component: BasicLayout,
  redirect: redirectFunc,
  children: [],
  meta: { title: '主页' }
}

// 防抖控制对象
const debounceControl = {
  lastCallTime: 0,
  isGenerating: false,
  pendingResolve: null,
  pendingReject: null
}

/**
 * 根路径重定向函数
 */
function redirectFunc() {
  const userStore = useUserStore()
  let mainPageUri = ''
  
  userStore.userInfo.allMenuRouteTree.forEach((item) => {
    if (item.entId === 'ENT_C_MAIN') {
      mainPageUri = item.menuUri
      return false
    }
  })

  return mainPageUri || getFirstAvailableUri(userStore.userInfo.allMenuRouteTree)
}

/**
 * 获取第一个可用的路由路径
 */
function getFirstAvailableUri(menuItems) {
  for (const item of menuItems) {
    if (item.menuUri && item.entType === 'ML') {
      return item.menuUri
    }
    if (item.children) {
      const childUri = getFirstAvailableUri(item.children)
      if (childUri) return childUri
    }
  }
  return ''
}

/**
 * 动态生成路由（优化后的防抖实现）
 */
export const generatorDynamicRouter = () => {
  return new Promise((resolve, reject) => {
    const now = Date.now()
    
    // 如果正在生成中，保存回调等待完成
    if (debounceControl.isGenerating) {
      debounceControl.pendingResolve = resolve
      debounceControl.pendingReject = reject
      return
    }
    
    // 防抖检查
    if (now - debounceControl.lastCallTime < DEBOUNCE_TIME) {
      const remainingTime = ((DEBOUNCE_TIME - (now - debounceControl.lastCallTime)) / 1000).toFixed(1)
      message.warning(`路由操作过于频繁，请${remainingTime}秒后再试`)
      return reject(new Error(`TOO_FREQUENT_OPERATION`))
    }
    
    // 标记为正在生成
    debounceControl.isGenerating = true
    debounceControl.lastCallTime = now
    
    generateRoutes()
      .then(result => {
        resolve(result)
        // 处理等待中的请求
        if (debounceControl.pendingResolve) {
          debounceControl.pendingResolve(result)
        }
      })
      .catch(error => {
        reject(error)
        // 处理等待中的请求
        if (debounceControl.pendingReject) {
          debounceControl.pendingReject(error)
        }
      })
      .finally(() => {
        // 重置状态
        debounceControl.isGenerating = false
        debounceControl.pendingResolve = null
        debounceControl.pendingReject = null
      })
  })
}

/**
 * 实际执行路由生成的函数
 */
function generateRoutes() {
  return new Promise((resolve, reject) => {
    try {
      const userStore = useUserStore()
      rootRouter.children = generateRouteNodes(userStore.userInfo.allMenuRouteTree)
      resolve([rootRouter, notFoundRouter])
    } catch (error) {
      console.error('路由生成失败:', error)
      reject(error)
    }
  })
}

/**
 * 递归生成路由节点
 */
export const generateRouteNodes = (menuNodes) => {  
  return menuNodes
    .map(item => {
      const componentDef = constantRouterComponents[item.componentName || item.entId]
      
      if (!componentDef || 
          (item.componentName === 'RouteView' && (!item.children || item.children.length === 0))) {
        return null
      }

      const path = item.menuUri || 
                 (item.children?.length > 0 ? `/${item.entId}` : null)
      
      if (!path) return null

      const route = {
        path,
        name: item.entId,
        component: componentDef?.component || (() => import(`@/views/${item.componentName}`)),
        meta: {
          title: item.entName,
          icon: `${item.menuIcon}-outlined`,
          keepAlive: false,
          hideInMenu: item.entType === 'MO'
        }
      }

      if (item.children?.length > 0) {
        route.children = generateRouteNodes(item.children)
        if (item.componentName === 'RouteView' && route.children.length === 0) {
          return null
        }
      }

      return route
    })
    .filter(Boolean)
}

export default {
  constantRouterComponents,
  notFoundRouter,
  rootRouter,
  generatorDynamicRouter,
  generateRouteNodes
}